<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8"/>
    <meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
          name="viewport">
    <title>系统公告管理</title>
    <script th:src="@{/echarts/jquery-1.11.1.min.js}"></script>
    <link media="all" rel="stylesheet" th:href="@{/layui/css/layui.css}">
    <script charset="utf-8" th:src="@{/layui/layui.js}"></script>
    <style>
        body {
            margin: 10px;
            /* 去掉不必要的 text-align: center */
        }

        /* 调整日期范围选择器的样式 */
        .layui-input-inline {
            width: 150px;
        }

        /* 为按钮添加右外边距 */
        button {
            margin-right: 1px;
        }

        /* 移除最后一个按钮的右外边距 */
        button:last-child {
            margin-right: 0;
        }

        .layui-form-item {
            margin-bottom: 15px;
        }

        .layui-form-label {
            width: 100px;
            font-weight: 500;
            color: #333;
        }

        .layui-input-block {
            margin-left: 50px;
        }

        .layui-textarea {
            border-radius: 4px !important;
            border-color: #e6e6e6;
            height: 150px;
        }

        /* 调整日期范围选择器的样式 */
        .layui-input-inline {
            width: 150px;
        }

        /* 定义表格父容器的样式，使其成为弹性布局容器，并将子元素居中 */
        .table-container {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-top: 50px; /* 可根据需要调整表格与上方搜索框的间距 */
        }

        .table-container-search {
            /*margin-right: 20px; !* 可根据需要调整搜索框与表格的间距 *!*/
            /*margin-left: 50px;*/
            padding-top: 15px;
            margin-bottom: -20px;
        }

    </style>
</head>
<body class="childrenBody">
<!-- 模态窗：添加、修改 -->
<div id="addOrUpdateDiv" style="display: none;padding: 10px 5% 10px 10px;">
    <form action="" class="layui-form" id="addOrUpdateFrm" lay-filter="addOrUpdateFrm" lay-verify="required"
          method="post">
        <input name="id" type="hidden" value=""> <!--隐藏Id 输入框-->

        <div class="layui-form-item">
            <fieldset class="layui-elem-field layui-field-title" style="margin-left: 30px">
                <span style="color: red;">*</span>标题
            </fieldset>
            <div class="layui-input-block">
                <input class="layui-input" lay-verify="required" name="title" placeholder="请输入标题" type="text">
            </div>
        </div>

        <div class="layui-form-item">
            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;margin-left: 30px">
                <span style="color: red;">*</span>内容
            </fieldset>
            <div class="layui-input-block">
                <!-- 富文本编辑器容器 -->
                <textarea class="layui-textarea" lay-verify="required" name="content"
                          placeholder="请输入内容"></textarea>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label" style="margin-left: -50px;padding-right: 30px">
                <span style="color: red;">*</span>类型
            </label>
            <div class="layui-input-block">
                <input checked="" name="type" title="通知" type="radio" value="1">
                <input name="type" title="公告" type="radio" value="2">
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block" style="text-align: right;">
                <button class="layui-btn layui-btn-normal layui-btn-radius" lay-filter="addOrUpdateFrm" lay-submit="">
                    <i class="layui-icon layui-icon-addition"></i> 保存
                </button>
                <button class="layui-btn layui-btn-radius layui-btn-warm" type="reset">
                    <i class="layui-icon layui-icon-refresh"></i><span>重置</span>
                </button>
                <button class="layui-btn layui-btn-secondary layui-btn-radius" id="close" type="button">
                    <i class="layui-icon layui-icon-close"></i> 取消
                </button>
            </div>
        </div>
    </form>
</div>


<div class="table-container-search" style="padding: 10px;">
    <!-- 内容主体区域 -->
    <!-- 搜索条件 -->
    <fieldset class="layui-elem-field layui-field-title">
        <legend>搜索条件</legend>
    </fieldset>
    <form action="" class="layui-form" id="searchFrm" lay-filter="searchFrm" method="post">
        <div class="layui-inline">
            <label class="layui-form-label">标题：</label>
            <div class="layui-input-inline">
                <input class="layui-input input-radius" id="title" name="title" placeholder="请输入标题"
                       type="text">
            </div>
        </div>
        <div class="layui-inline">
            <!--类型(1 通知 2 公告)-->
            <label class="layui-form-label">类型：</label>
            <div class="layui-input-inline">
                <select id="type" name="type">
                    <option value="">请选择类型</option>
                    <option value="1">通知</option>
                    <option value="2">公告</option>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <!--状态(0 正常 1 关闭 2 待发布)-->
            <label class="layui-form-label">状态：</label>
            <div class="layui-input-inline">
                <select id="status" name="status">
                    <option value="">请选择状态</option>
                    <option value="0">正常</option>
                    <option value="1">关闭</option>
                    <option value="2">待发布</option>
                </select>
            </div>
        </div>
        <div class="layui-inline" style="padding-left: 10px">
            <button class="layui-btn layui-btn-sm layui-btn-radius" lay-filter="doSearch" lay-submit=""
                    type="button">
                <i class="layui-icon layui-icon-search layui-icon-normal"></i>查询
            </button>
            <button class="layui-btn layui-btn-sm layui-btn-radius layui-btn-warm" lay-filter="doSearch"
                    lay-submit="" type="reset">
                <i class="layui-icon layui-icon-refresh"></i><span>重置</span>
            </button>
        </div>
    </form>
    <br>
    <hr>
</div>

<div class="table-container">
    <!-- table -->
    <table class="layui-hide" id="demo" lay-filter="test"></table>
</div>

<!--编辑、发布、关闭、删除javascript模块-->
<script id="barDemo" type="text/html">
    <button type="button" lay-event="update" class="layui-btn layui-btn-sm layui-btn-radius">
        <i class="layui-icon layui-icon-edit"></i>编辑
    </button>
    <button type="button" lay-event="publish" class="layui-btn layui-btn-sm layui-btn-radius layui-btn-warm">
        <i class="layui-icon layui-icon-auz"></i>发布
    </button>
    <button type="button" lay-event="close" class="layui-btn layui-btn-sm layui-btn-radius layui-bg-black">
        <i class="layui-icon layui-icon-tips"></i>关闭
    </button>
    <button type="button" lay-event="delete" class="layui-btn layui-btn-sm layui-btn-radius layui-btn-danger">
        <i class="layui-icon layui-icon-delete"></i>删除
    </button>
</script>

<!-- 定义自定义模板 -->
<script id="toolbarDemo" type="text/html">
    <div class="layui-btn-container">
        <button class="layui-icon layui-icon-add-1" lay-event="add">新增</button>
        <button class="layui-icon layui-icon-delete" lay-event="batchDelete">批量删除</button>
    </div>
</script>


<!-- 自定义模版工具栏 新增、批量删除-->
<div th:include="commonmenu :: toolbarDemo"></div>

<script>
    layui.config({
        version: '1632428048355' //为了更新 js 缓存，可忽略
    });

    var url;
    var tableIns;
    var mainIndex;

    //加载模块
    layui.use(["upload", "jquery", "laypage", "table", "form", "element", "util", "laydate"], function () { //亦可加载特定模块：layui.use(['layer', 'laydate', function(){
        //得到各种内置组件
        var layer = layui.layer //弹层
            , upload = layui.upload //拖拽上传
            , $ = layui.jquery
            , laypage = layui.laypage //分页
            , table = layui.table //表格
            , form = layui.form //表单
            , element = layui.element //元素操作
            , util = layui.util
            , laydate = layui.laydate   // 日期选择器

        form.render();  // 初始化渲染表单

        //监听Tab切换
        element.on('tab(demo)', function (data) {
            layer.tips('切换了 ' + data.index + '：' + this.innerHTML, this, {
                tips: 1
            });
        });

        //执行一个 table 实例
        tableIns = table.render({
            elem: '#demo'
            , url: '/notice/selectAllNotice' //数据接口
            , title: '系统公告表'
            , page: true //开启分页
            , width: 1600
            , height: "full-300"
            , toolbar: '#toolbarDemo' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
            , totalRow: false //开启合计行
            , cols: [ [ //表头
                {type: 'checkbox', fixed: 'left'}
                , {field: 'id', title: 'ID', width: 50, fixed: 'left', totalRowText: '合计：', hide: true}
                , {field: 'title', title: '标题', width: 190}
                /*类型(1通知 2公告)*/
                , {
                    field: 'type', title: '类型', width: 80, templet: d =>
                        `<span class="layui-badge ${d.type == 1 ? 'layui-bg-blue' : 'layui-bg-red'}">${d.type == 1 ?
                            '通知' : '公告'}</span>`
                }
                , {field: 'content', title: '内容', width: 330}
                , {
                    field: 'status', title: '状态', width: 80, templet: function (d){
                        switch (d.status){
                            case '0':
                                return `<span class="layui-badge layui-bg-green">正常</span>`
                            case '1':
                                return `<span class="layui-badge layui-bg-black">关闭</span>`
                            case '2':
                                return `<span class="layui-badge layui-bg-blue">待发布</span>`
                            case '3':
                                return `<span class="layui-badge layui-bg-red">异常</span>`
                            default:
                                return `<span class="layui-badge layui-bg-gray">未知状态</span>`
                        }
                    }
                }
                , {field: 'createdUser', title: '创建者', width: 100}
                , {
                    field: 'createTime', title: '创建时间', width: 160, sort: true, templet: function (d) {
                        // 手动定义格式化时间
                        var date = new Date(d.createTime);
                        var year = date.getFullYear();
                        var month = String(date.getMonth() + 1).padStart(2, '0');
                        var day = String(date.getDate()).padStart(2, '0');
                        var hours = String(date.getHours()).padStart(2, '0');
                        var minutes = String(date.getMinutes()).padStart(2, '0');
                        var seconds = String(date.getSeconds()).padStart(2, '0');
                        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                    }
                }
                , {field: 'modifiedUser', title: '更新者', width: 100}
                , {
                    field: 'modifiedTime', title: '更新时间', width: 160, sort: true, templet: function (d) {
                        // 手动定义格式化时间
                        var date = new Date(d.modifiedTime);
                        var year = date.getFullYear();
                        var month = String(date.getMonth() + 1).padStart(2, '0');
                        var day = String(date.getDate()).padStart(2, '0');
                        var hours = String(date.getHours()).padStart(2, '0');
                        var minutes = String(date.getMinutes()).padStart(2, '0');
                        var seconds = String(date.getSeconds()).padStart(2, '0');
                        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                    }
                }
                , {field: 'remark', title: '备注', width: 150, hide: true}
                , {fixed: 'right', width: 340, align: 'center', toolbar: '#barDemo'}
            ] ]
        });

        //监听头工具栏事件 新增和批量删除
        table.on('toolbar(test)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id)
            var data = checkStatus.data; //获取选中的数据
            switch (obj.event) {
                case 'add':
                    //调出弹窗
                    openAddLayer();
                    break;

                case 'batchDelete':
                    if (data.length === 0) {
                        layer.msg('请至少选择一行');
                    } else {
                        layer.confirm('真的要删除选中的 ' + data.length + ' 条数据吗？', {
                            btn: ['删除', '取消']
                        }, function (index) {
                            // 发送批量删除请求
                            $.ajax({
                                url: '/notice/batchDelete',
                                type: 'POST',
                                // contentType: 'application/json',
                                // data: JSON.stringify(data.map(item => item.id)),
                                success: function (res) {
                                    if (res.code === 200) {
                                        layer.msg('批量删除成功', {icon: 1});
                                        tableIns.reload(); // 刷新表格
                                    } else {
                                        layer.msg('批量删除失败：' + res.msg, {icon: 5});
                                    }
                                },
                                error: function (xhr, status, error) {
                                    layer.msg('网络请求失败，请重试', {icon: 5});
                                }
                            });
                        });
                    }
                    break;
            }
        });

        //编辑、发布、关闭、删除    监听行工具事件
        table.on('tool(test)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
                , layEvent = obj.event; //获得 lay-event 对应的值
            if (layEvent === 'update') {
                // 更新的逻辑代码
                openUpdateLayer(data)
            } else if (layEvent === 'publish') {
                layer.confirm('确定要发布该公告/通知么？', function (index) {
                    obj.update(); //删除对应行（tr）的DOM结构
                    //向服务端发送删除指令
                    $.post("/notice/publishNotice", {id: obj.data.id}, function (res) {
                        if (res.code == 200) {
                            tableIns.reload({
                                where: "",
                            });
                        }
                        layer.msg(res.msg)
                    })
                    layer.close(index);
                });
            } else if (layEvent === 'close') {
                layer.confirm('确定要关闭该公告/通知么？', function (index) {
                    obj.update(); //更新对应行（tr）的DOM结构
                    //向服务端发送删除指令
                    $.post("/notice/closeNotice", {id: obj.data.id}, function (res) {
                        if (res.code == 200) {
                            tableIns.reload({
                                where: "",
                            });
                        }
                        layer.msg(res.msg)
                    })
                    layer.close(index);
                });
            } else if (layEvent === 'delete') {
                layer.confirm('真的删除行么？', function (index) {
                    obj.del(); //删除对应行（tr）的DOM结构
                    //向服务端发送删除指令
                    $.post("/notice/deleteById", {id: obj.data.id}, function (res) {
                        if (res.code == 200) {
                            tableIns.reload({
                                where: "",
                            });
                        }
                        layer.msg(res.msg)
                    })
                    layer.close(index);
                });
            }
        });

        //打开添加弹出层
        function openAddLayer() {
            mainIndex = layer.open({
                type: 1,
                content: $("#addOrUpdateDiv"),
                area: ['750px', '630px'],
                title: '新增公告/通知信息',
                success: function () {
                    $("#addOrUpdateFrm")[0].reset();
                    url = "/notice/addNotice";
                }
            });
        }

        //打开修改的弹出层
        function openUpdateLayer(data) {
            mainIndex = layer.open({
                type: 1,
                content: $("#addOrUpdateDiv"),
                area: ['750px', '630px'],
                title: '编辑公告/通知信息',
                success: function () {
                    //清空原有的数据
                    $("#addOrUpdateFrm")[0].reset();
                    //装载新的数据
                    form.val("addOrUpdateFrm", data);
                    url = "/notice/updateNotice";
                }
            });
        }

        form.on("submit(addOrUpdateFrm)", function (data) {
            $.post(url, data.field, function (res) {
                if (res.code === 200) {
                    tableIns.reload();
                    layer.close(mainIndex);
                }
                layer.msg(res.msg);
            });
            return false;
        });

        //模糊查询
        form.on("submit(doSearch)", function (data) {
            var startDate = $('#test-startDate-1').val()
                ,endDate = $('#test-endDate-1').val();
            data.field.startDate = startDate;
            data.field.endDate = endDate;
            tableIns.reload({
                where: data.field,
                page: {
                    curr: 1
                }
            });
            return false;
        })

        //取消按钮点击绑定，关闭弹窗
        $('#close').on('click', function (e) {
            {
                layer.close(mainIndex)
            }
        })

        //分页
        laypage.render({
            elem: 'pageDemo' //分页容器的id
            , count: 1000 //数据总数
            , limit: 10 //每页显示的数据条数
            , skin: '#1E9FFF' //自定义选中色值
            //,layout: ['prev', 'page', 'next', 'count', 'limit', 'refresh', 'skip'] //自定义排版
            , jump: function (obj, first) {
                if (!first) {
                    layer.msg('第' + obj.curr + '页', {offset: 'b'});
                }
            }
        });

    })
</script>
</body>
</html>